package com.miaoxie.forum.module.auth.shared.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.miaoxie.forum.module.auth.shared.controller.ResponseMessageController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import com.miaoxie.forum.module.auth.shared.constants.DefinitionKeys;
import com.miaoxie.forum.module.auth.shared.utils.JSONBuilder;

/**
 * Created by miaoxie on 2017/2/06.
 * <p/>
 * 权限管理过滤器
 */
public class AuthFilter  implements Filter {

    private static Logger log = LoggerFactory.getLogger(AuthFilter.class);
    /*
        缓存从spring容器中获取的对象
     */
    private static volatile ApplicationContext applicationContext = null;


    private static final String[] OPEN_URL = {"/version/", "/imgCtroller/"};

    private volatile String[] escapeUrls;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 允许跨域访问
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setCharacterEncoding("UTF-8");
        /**
         * 系统分为三类请求，一类是前往后台管理，另外一类是前往业务数据请求，还有一类是开发性接口，不需要登陆验证
         * 1. 如果请求路径是后台管理，则检查session，控制登录
         * 2. 如果是业务接口请求，不进行session检查，一律放行
         * 3. 如果是开发性接口，不进行session检查，不进行用户校验
         *
         * 注意：两种请求都设置session， session中只保留用户工号；
         *      两种请求都需要在UserContext中存储当前会话用户，在会话结束时清除。
         */
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession httpSession = req.getSession();
        String requestURL = req.getRequestURL().toString();

        /*
            如果配置在escapeUrls中则跳过检查；
        */
        if (requestURL.contains(DefinitionKeys.MONITOR_URL)) {
            filterChain.doFilter(request, response);
        } else {
            try {
                        /*
                            授权失败
                        */
                String json = JSONBuilder.builder()
                        .inflate(ResponseMessageController.PROTOCOL_MESSAGE, "Not Authorized.")
                        .inflate(ResponseMessageController.PROTOCOL_SUCCESS, false)
                        .inflate(ResponseMessageController.PROTOCOL_EXCEPTION, false)
                        .build()
                        .toString();
                res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                res.getWriter().write(json);
            } finally {
                // 清除ThreadLocal中持有的信息
            }
        }
    }

    @Override
    public void destroy() {

    }

    private enum RequestForward {
        MANAGER_PAGE,
        RESTFULL_INTERFACE
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String escapeStr = filterConfig.getInitParameter("escapeUrls");
        escapeUrls = escapeStr.split(",");
    }
}
